package com.shopnight.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.shopnight.config.WxPayConfig;
import com.shopnight.constant.ShopIndentConstant;
import com.shopnight.entity.*;
import com.shopnight.interceptors.JWTInterceptor;
import com.shopnight.mapper.*;
import com.shopnight.result.ApiResult;
import com.shopnight.service.*;
import com.shopnight.utils.*;
import com.shopnight.vo.*;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import java.util.concurrent.*;
import java.util.stream.Collectors;


/**
 * @author 13201
 * @description 针对表【shop_indent】的数据库操作Service实现
 * @createDate 2022-09-08 22:20:51
 */
@Service
@Slf4j
//TODO可以试着优化这一层
public class ShopIndentServiceImpl extends ServiceImpl<ShopIndentMapper, ShopIndent> implements ShopIndentService{

    @Autowired
    JavaMailSender MailSender;
    @Autowired
    ShopGoodsMapper shopGoodsMapper;
    @Autowired
    ShopIndentMapper shopIndentMapper;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    ShopOrderMapper shopOrderMapper;
    @Autowired
    ShopAddressService addressService;
    @Autowired
    IImageService imageService;
    @Autowired
    ShopGoodsService goodsService;
    @Autowired
    ShopOrderService orderService;
    @Autowired
    CartService cartService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    OrganizationMapper organizationMapper;

    @Autowired
    WxPayConfig wxPayConfig;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ErrandOrderService errandOrderService;
    @Autowired
    private AllOrderMapper allOrderMapper;
    @Autowired
    private AllOrderUtil allOrderUtil;
    @Autowired
    private MyMQTTClient myMQTTClient;

    @Autowired
    @Resource(name = "taskExecutor")
    Executor executor;

    private String prefix = "snack-order:";

    @Override
    @Transactional
    public ApiResult addIndent(AddIndentVo addIndentVo) throws Exception {
        //首先读取用户id 防止瞬间用户id被覆盖
        Integer userId = Integer.valueOf(UserContext.getEndUserId());
        if (addIndentVo == null)  return ApiResult.fail("请传入订单参数！");
        List<Goods> goodsList = addIndentVo.getGoods();
        if (! (goodsList.size() > 0) )  return  ApiResult.fail("请提交商品！");

        BigDecimal priceAll  = new BigDecimal("0") ;
        List<String> orderName = new ArrayList<>();
        List<Stock>  Stocks = new ArrayList<>();
        BigDecimal deliveryPrices = new BigDecimal(0);

        for ( Goods item : goodsList ){
            ShopOrder order = shopOrderMapper.selectById(item.getOrderId());
            if(order.getSeckill() == 1){
                BigDecimal priceSeckill = order.getPriceSeckill();
                item.setPurchasePrice( priceSeckill );
                priceAll = priceAll.add( priceSeckill.multiply( new BigDecimal(item.getOrderNum()) ) )  ;
            }else {
                BigDecimal priceDiscounts = order.getPriceDiscounts();
                item.setPurchasePrice( priceDiscounts );
                priceAll = priceAll.add( priceDiscounts.multiply( new BigDecimal(item.getOrderNum()) ) )  ;
            }
            Stock stock = stockMapper.selectOne(
                    new LambdaQueryWrapper<Stock>().eq(Stock::getOrderId,item.getOrderId())
            );
            //判断库存数量是否大于购买数量
            if (item.getOrderNum() > stock.getStockCount())
                orderName.add(shopOrderMapper.selectById(item.getOrderId()).getOrderName());

            Stocks.add(stock);
        }

        //查询组织信息
        Organization organization = organizationMapper.selectById(addIndentVo.getOrgId());
        //计算订单价格与配送费
        if( (priceAll.compareTo( organization.getStartingFare() ) == -1) &&  addIndentVo.getOneself() == 1 ){
                priceAll = priceAll.add(organization.getDeliveryPrices());
                deliveryPrices = organization.getDeliveryPrices();
        };

        if ( priceAll.compareTo(addIndentVo.getPrices()) != 0  ) return ApiResult.fail("订单价格不符 请刷新页面重试!");
        if (!orderName.isEmpty())  return ApiResult.fail(orderName + "库存不足！");

//雪花算法生成订单号
        String code = new Snowflake().nextIdStr();
        User user = userMapper.selectById(userId);
        Integer amount = ( priceAll.multiply(new BigDecimal("100")) ).intValue();
        String response= WxMiniPayUtils.creatOrderJSAPI( user.getOpenId() , code, amount,ShopIndentConstant.orderTypeEnum.shop.getTyep(),"零食支付" );
        JSONObject jsonObject = JSONObject.parseObject(response);

        if (jsonObject.containsKey("prepay_id")){
            //库存操作
            Stocks.forEach( stockItem -> {
                goodsList.forEach( goods -> {
                    if ( stockItem.getOrderId().intValue() ==  goods.getOrderId() )
                        stockItem.setStockCount( stockItem.getStockCount() - goods.getOrderNum() );
                });
                if( stockMapper.updateById(stockItem) == 0 ){
                    //更新库存失败
                    Stock stock = stockMapper.selectById(stockItem.getStockId());
                    //再次查询并更新
                    stock.setStockCount(stockItem.getStockCount());
                    if( stockMapper.updateById(stock) == 0 ){
                        throw new RuntimeException ("服务器繁忙！请重试");
                    }
                }
            });

            Date date = new Date();

            //赋值订单号
            addIndentVo.setIndentCode(code);
            ShopIndent shopIndent = new ShopIndent();
            BeanUtils.copyProperties(addIndentVo,shopIndent );
            shopIndent.setDeliveryPrices(deliveryPrices );
            shopIndent.setCreateTime(date);
            shopIndent.setIndentStatus(ShopIndentConstant.StatusEnum.unpaid.getStatus());
            shopIndent.setUserId(userId);

            //赋值地址
            ShopAddress address = addressService.selectAddress(addIndentVo.getAddressId());
            shopIndent.setConsignee(address.getConsignee());
            shopIndent.setConsigneePhone(address.getConsigneePhone());
            shopIndent.setDetailedAddress(address.getDetailedAddress());

            shopIndentMapper.insert(shopIndent);
            //赋值生成后的订单id
            addIndentVo.setIndentId(shopIndent.getIndentId());

           //插入订单顺序记录表
            AllOrder allOrder = new AllOrder();
            allOrder.setUserId(userId);
            allOrder.setOrderId(Integer.valueOf(shopIndent.getIndentId().toString()));
            allOrder.setOrderCode(code);
            allOrder.setOrderType(ShopIndentConstant.orderTypeEnum.shop.getTyep());
            allOrder.setOrderStatus(ShopIndentConstant.StatusEnum.unpaid.getStatus());
            allOrder.setOrgId(shopIndent.getOrgId());
            allOrder.setCreateTime(date);
            allOrderMapper.insert(allOrder);


            //异步删除购物车
          //  CompletableFuture.runAsync(()->{
                for ( Goods item : goodsList ){
                    ShopGoods shopGoods = new ShopGoods();
                    BeanUtils.copyProperties( item , shopGoods );
                    shopGoods.setIndentId( shopIndent.getIndentId() );
                    try {
                        shopGoodsMapper.insert(shopGoods);
                        //删除商品购物车
                        cartService.deleteItem(Long.valueOf(item.getOrderId()));
                    }catch (Exception e){
                        throw new RuntimeException (e.getMessage());
                    }
                }
         //   },executor);



            //已提交腾讯待支付订单
            String prepay_id = jsonObject.get("prepay_id").toString();
            String WxSign = WxSignUtil.getWxAppPayTuneUp(prepay_id);
            JSONObject resJsonObject = JSON.parseObject(WxSign);
            resJsonObject.put("shopIndentId",shopIndent.getIndentId());
            JSONObject redisJson = new JSONObject();
            redisJson.put("pay",resJsonObject);
            redisJson.put("emali",addIndentVo);

            //待支付订单存入redis 30, TimeUnit.MINUTES
            stringRedisTemplate.opsForValue().set(prefix + code, JSON.toJSONString(redisJson),30, TimeUnit.MINUTES);

            return ApiResult.ok("订单创建成功！",resJsonObject);
        }else {
            throw new RuntimeException ("订单提交失败！");
        }




    }


    public IPage getUserOrderList(Map<String,String> map) {
        //读取用户id
        String userId =  UserContext.getEndUserId();

        LambdaQueryWrapper<AllOrder> lqw = new LambdaQueryWrapper();
        lqw.eq(AllOrder::getUserId,userId)
                .eq( map.containsKey("orderStatus")   ,AllOrder::getOrderStatus,map.get("orderStatus"))
                .orderBy(true,false,AllOrder::getCreateTime);
        IPage<AllOrder> page = new Page<>(Long.valueOf(map.get("current")),Long.valueOf(map.get("pageSize")) );
        IPage<AllOrder> res = allOrderMapper.selectPage(page, lqw);
        if (! (res.getRecords().size() > 0)) return res ;

        List<Object> Records = new ArrayList<Object>();
        List<Integer> indentIds = new ArrayList<Integer>();
        List<Integer> errandIds = new ArrayList<Integer>();


        res.getRecords().stream().forEach(order->{
            switch ( order.getOrderType() ) {
                case 1:    // 处理零食订单
                    indentIds.add(order.getOrderId());
                    break;
                case 2:   // 处理跑腿订单
                    errandIds.add(order.getOrderId());
                    break;
                default:
                    log.info("未知的支付类型");
                    break;
            }
        });
        //获取零食订单数据
        if (indentIds.size() > 0 )  getIndent(Records,indentIds);

        //获取跑腿订单数据
        if (errandIds.size() > 0 )  errandOrderService.getUserErandOrderList(Records,errandIds);


        List<JSONObject> collect = Records.stream().map(item -> {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(item);
            return jsonObject;
        }).sorted((item1,item2)->{
                        return  (((Date)item2.get("createTime")).getTime() - ((Date)item1.get("createTime")).getTime()) > 0 ? 1 : -1;
                })
        .collect(Collectors.toList());

        Page<JSONObject> UserOrderList = new Page<JSONObject>();
        UserOrderList.setCurrent(page.getCurrent());
        UserOrderList.setPages(page.getPages());
        UserOrderList.setSize(page.getSize());
        UserOrderList.setTotal(page.getTotal());
        UserOrderList.setRecords(collect);
        return UserOrderList;
    }

    @Override
    public ApiResult getUserOrderStatusNumber() {
        String userId =  UserContext.getEndUserId();
        return  ApiResult.ok(
                shopIndentMapper.getUserIndentStatusNumber(userId)
                        .stream()
                        .collect(Collectors.toMap(
                                item -> item.get("order_status"),
                                item -> item.get("sum")
                        ))
        );
    }

    public ApiResult getIndentInfo(Map<String,Long> map){
        ShopIndent shopIndent = shopIndentMapper.selectById(map.get("indentId"));
        IndentInfoVO indentInfoVO = new IndentInfoVO();
        BeanUtils.copyProperties(shopIndent,indentInfoVO);

        Organization organization = organizationMapper.selectById(shopIndent.getOrgId());
        indentInfoVO.setOrgName( organization.getOrgName() );

        //判断是否有接单管理员
        if (shopIndent.getAdminId() != null){
            Admin admin = adminMapper.selectById(shopIndent.getAdminId());
            indentInfoVO.setAdminName(admin.getAdminName());
            indentInfoVO.setAdminPhone(admin.getAdminPhone());
        }

        //判断该订单是否是待付款
        if(shopIndent.getIndentStatus() == ShopIndentConstant.StatusEnum.unpaid.getStatus()){
            //查询redis里 此订单取消的时间
            Long expire = stringRedisTemplate.opsForValue().getOperations().getExpire(prefix + shopIndent.getIndentCode());
            String wxpay = stringRedisTemplate.opsForValue().get(prefix + shopIndent.getIndentCode());
            indentInfoVO.setWxpay((JSONObject) JSON.parseObject(wxpay).get("pay"));
            indentInfoVO.setExpire(expire);
        }

        indentInfoVO.setGoodsList(
                shopGoodsMapper.selectList(
                                new LambdaQueryWrapper<ShopGoods>()
                                        .eq(ShopGoods::getIndentId,indentInfoVO.getIndentId())
                        )
                        .parallelStream().map( item -> {
                            IndentInfoVO.GoodsVO goodsVO = new IndentInfoVO.GoodsVO();
                            goodsVO.setOrderNum(item.getOrderNum());
                            goodsVO.setPurchasePrice(item.getPurchasePrice());
                            ShopOrder order = shopOrderMapper.selectById(item.getOrderId());
                            goodsVO.setOrderId(order.getOrderId());
                            goodsVO.setOrderName(order.getOrderName());
                            goodsVO.setPrice(order.getPrice());
                            goodsVO.setSeckill(order.getSeckill());
                            goodsVO.setPriceSeckill(order.getPriceSeckill());
                            goodsVO.setPriceDiscounts(order.getPriceDiscounts());
                            goodsVO.setOrgId(order.getOrgId());

                            Integer stockCount = stockMapper
                                    .selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getOrderId, order.getOrderId()))
                                    .getStockCount();
                            goodsVO.setStockCount(stockCount);

                            goodsVO.setImgUrl(
                                    imageService.getOne(
                                            new LambdaQueryWrapper<Image>()
                                                    .eq(Image::getOrderId,item.getOrderId())
                                                    .eq(Image::getDefaultImg,1)
                                    ).getImgUrl()
                            );

                            return goodsVO;
                        }).collect(Collectors.toList())
        );

        return ApiResult.ok(indentInfoVO) ;
    }

    @Override
    @Transactional
    public ApiResult UpdateIndent(ShopIndent shopIndent) throws IOException {
        String userId = UserContext.getEndUserId();
        if (shopIndent == null || shopIndent.getIndentId() == null)  return ApiResult.fail("无效参数请求！");

        User user = userMapper.selectById(userId);

        ShopIndent dbShopIndent = shopIndentMapper.selectById(shopIndent);


        //当不为管理员时 不可修改其他用户信息
        if ( user.getAdminId() == null ){
            if (! dbShopIndent.getUserId().toString().equals( userId ) ) return ApiResult.fail("请勿更改他人订单！");
        }

        //如果是取消订单的时候
        if (shopIndent.getIndentStatus()!=null && shopIndent.getIndentStatus() == ShopIndentConstant.StatusEnum.cancel.getStatus() ){

            if( !(dbShopIndent.getIndentStatus() ==  ShopIndentConstant.StatusEnum.underway.getStatus() || dbShopIndent.getIndentStatus() ==  ShopIndentConstant.StatusEnum.unpaid.getStatus() ))  return ApiResult.fail("订单状态不可更改！");

            if ( dbShopIndent.getIndentStatus() == ShopIndentConstant.StatusEnum.underway.getStatus() && dbShopIndent.getAdminId() == null){
                String outRefundNo = new Snowflake().nextIdStr();
                //退钱 异步线程
               // CompletableFuture.runAsync(()->{
                    JSONObject domesticRefundsJSON = new JSONObject();
                    domesticRefundsJSON.put("transaction_id", dbShopIndent.getTransactionId());
                    //雪花算法生成退款订单号
                    domesticRefundsJSON.put("out_refund_no", outRefundNo);
                    domesticRefundsJSON.put("reason","网超零食订单退款");
                    JSONObject amount = new JSONObject();
                    amount.put("refund", (dbShopIndent.getPrices().multiply(new BigDecimal("100"))).intValue()  );
                    amount.put("total",  (dbShopIndent.getPrices().multiply(new BigDecimal("100"))).intValue());
                    amount.put("currency","CNY");
                    domesticRefundsJSON.put("amount",amount);
                    domesticRefundsJSON.put("notify_url", wxPayConfig.getRefundsNotifyDomain() );
                    String parm = domesticRefundsJSON.toJSONString();
                    try {
                        WxMiniPayUtils.v3Post("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds", parm);
                        //更改腾讯订单为取消状态
                        WxMiniPayUtils.closeOrder(dbShopIndent.getIndentCode());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
              //  },executor);

                //更改订单状态为已退款
                shopIndent.setIndentStatus(ShopIndentConstant.StatusEnum.refunded.getStatus());
                shopIndent.setOutRefundNo(outRefundNo);

            }else if (dbShopIndent.getIndentStatus() == ShopIndentConstant.StatusEnum.underway.getStatus() && dbShopIndent.getAdminId() != null){
               return ApiResult.fail("已接单 退款请联系配送员！");
            }



            List<ShopGoods> shopGoodsList = shopGoodsMapper.selectList(
                    new LambdaQueryWrapper<ShopGoods>()
                            .eq(ShopGoods::getIndentId,shopIndent.getIndentId())
            );
            //还原库存
            shopGoodsMapper.updateStock(shopGoodsList);

            //更改订单顺序表状态
            allOrderUtil.updateAllOrderStatus(Integer.valueOf(shopIndent.getIndentId().toString()),ShopIndentConstant.StatusEnum.cancel.getStatus());

        }


        //订单配送员接单
        if( shopIndent.getAdminId() != null && shopIndent.getAdminId().equals( "0" ) ){
            LambdaUpdateWrapper<ShopIndent> lambdaUpdate = Wrappers.lambdaUpdate();
            lambdaUpdate.eq(ShopIndent::getIndentId,shopIndent.getIndentId());
            lambdaUpdate.set(ShopIndent::getAdminId,null);
            shopIndent.setAdminId(null);
            shopIndentMapper.update(shopIndent,lambdaUpdate);
            return ApiResult.ok("更新成功");
        }else {
            Integer orgId = dbShopIndent.getOrgId();
            Organization organization = organizationMapper.selectById(orgId);


            List<Long> adminIdList = Arrays.stream(shopIndent.getAdminId().split(","))
                    .map(String::trim)
                    .map(Long::valueOf)
                    .collect(Collectors.toList());

            Admin admin = adminMapper.selectOne(
                    new LambdaQueryWrapper<Admin>()
                            .eq(Admin::getOrgId, organization.getId())
                            .in(Admin::getId, adminIdList )
            );
            shopIndent.setAdminId(String.valueOf(admin.getId()));

        }



        //更改订单主信息
        return  ApiResult.ok( shopIndentMapper.updateById(shopIndent) );
    }

    @Transactional
    @Override
    public void processOrder(String plainText) throws GeneralSecurityException {
///更改订单状态
/*
  根据订单号更新订单状态
  * @param orderNo
  @param orderStatus
 */
        //将明文转换成map
        Gson gson = new Gson();
        HashMap plainTextMap = gson.fromJson(plainText, HashMap.class);
        String orderNo = (String)plainTextMap.get("out_trade_no");

        //创建OrderInfo的queryWrapper
        LambdaQueryWrapper<ShopIndent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopIndent::getIndentCode,orderNo);
        ShopIndent shopIndent = shopIndentMapper.selectOne(queryWrapper);

        if(shopIndent.getIndentStatus() == ShopIndentConstant.StatusEnum.unpaid.getStatus() ){
            shopIndent.setIndentStatus( ShopIndentConstant.StatusEnum.underway.getStatus() );
            shopIndent.setTransactionId(plainTextMap.get("transaction_id").toString());
            shopIndentMapper.update(shopIndent, queryWrapper);

            //更改顺序表状态
            allOrderUtil.updateAllOrderStatus(Integer.valueOf(shopIndent.getIndentId().toString()),ShopIndentConstant.StatusEnum.underway.getStatus());

            String s = stringRedisTemplate.opsForValue().get(prefix + orderNo);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String emali = jsonObject.get("emali").toString();
            AddIndentVo addIndentVo = JSON.toJavaObject(JSONObject.parseObject(emali), AddIndentVo.class);


         //异步通知mqtt即时通讯
         CompletableFuture.runAsync(()->{
                Map<String,Object> map = new HashMap<>();
                map.put("type",1);
                map.put("msg","你有新的订单,请即时处理!");

                myMQTTClient.publish( JSON.toJSONString(map), "organization-snack-order:" + shopIndent.getOrgId() ,  1 );
            },executor);

         // 异步线程  在支付回调后发送邮件
           CompletableFuture.runAsync(()->{
               // 管理员邮件通知
               try {
                   SendAdminEmail(addIndentVo);
               } catch (MessagingException e) {
                   throw new RuntimeException(e);
               }
           },executor);


            //异步线程 删除redis的缓存key
            CompletableFuture.runAsync(()->{
                stringRedisTemplate.delete(prefix + orderNo);
            },executor);

            //异步线程 存储支付日志
            CompletableFuture.runAsync(()->{
                paymentInfoService.createPaymentInfo(plainText);
            },executor);

        }

    }


    //发送邮箱
    public void  SendAdminEmail(AddIndentVo addIndentVo) throws MessagingException {

//管理员邮件通知

        //随机图片的地址
        String[] img = {
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2014278.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2035567.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2046017.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2052796.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2053919.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2053942.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054350.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054480.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054618.jpg",
                "https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054956.jpg"
        };

            //根据id查询用户信息
            adminMapper.selectList(
                    new LambdaQueryWrapper<Admin>()
                            .eq(Admin::getOrgId,addIndentVo.getOrgId())
                            .eq(Admin::getReceiveEmail,1)
                            .eq(Admin::getStatus,1)
            ).parallelStream()
             .filter(admin-> StringUtils.hasLength( admin.getAdminMail() ) )
             .forEach( admin ->{
                 try {
                     //创建邮件消息
                     MimeMessage message = MailSender.createMimeMessage();
                     MimeMessageHelper helper = new MimeMessageHelper(message, true);
                     //谁发的
                     helper.setFrom("15555881410@163.com");
                     //谁要接收
                     helper.setTo(admin.getAdminMail());
                     //邮件标题
                     helper.setSubject("来新订单了！");
                     Map<String, Long> map = new HashMap<>();
                     map.put("indentId", addIndentVo.getIndentId());
                     String html = EmailHtml.AdminEmailHtml(
                             img[new Random().nextInt(10)],  //随机图片
                             admin.getAdminName(),
                            "ID "+ addIndentVo.getIndentId(),
                             EmailHtml.ContentHtml(getIndentInfo(map)),
                            "http://124.222.190.68/#/indent/index"
                     );
                     //设置内容
                     helper.setText(html, true);
                     MailSender.send(message);

                 } catch (MessagingException e) {
                     throw new RuntimeException(e);
                 }
             });



    }


    public  void getIndent(List<Object> list,List<Integer> indentIds){
        List<ShopIndent> shopIndentList = shopIndentMapper.selectList(
                new LambdaQueryWrapper<ShopIndent>().in(ShopIndent::getIndentId, indentIds)
        );

        List<ShopGoods> goodsList = goodsService.list(
                new LambdaQueryWrapper<ShopGoods>()
                        .in(ShopGoods::getIndentId, indentIds));
        List<Integer> orderIds = goodsList.stream().map(ShopGoods::getOrderId).collect(Collectors.toList());

        List<ShopOrder> shopOrders = orderService.list(
                new QueryWrapper<ShopOrder>().lambda()
                        .select(ShopOrder::getOrderId, ShopOrder::getOrderName)
                        .in(ShopOrder::getOrderId,orderIds)
        );

        List<Image> images = imageService.list(
                new QueryWrapper<Image>().lambda()
                        .eq(Image::getDefaultImg, 1)
                        .in(Image::getOrderId,orderIds));

        List<UserIndentVO> collect = shopIndentList.parallelStream().map(item -> {
            UserIndentVO indentVO = new UserIndentVO();
            BeanUtils.copyProperties(item, indentVO);

            //赋值订单类型
            indentVO.setOrderType(ShopIndentConstant.orderTypeEnum.shop.getTyep());
             //赋值组织名字
            indentVO.setOrgName(organizationMapper.selectById(item.getOrgId()).getOrgName());

            List<ShopGoods> goodsListFilter = goodsList.stream().filter(
                    goods ->  goods.getIndentId().equals(item.getIndentId())
            ).collect(Collectors.toList());

            indentVO.setGoodsList(goodsListFilter.stream().map(goods -> {
                UserIndentVO.GoodsVO goodsVO = new UserIndentVO.GoodsVO();
                shopOrders.forEach(order->{
                    if (order.getOrderId().equals(goods.getOrderId().longValue())){
                        goodsVO.setOrderName(order.getOrderName());
                    }
                });
                goodsVO.setOrderNum(goods.getOrderNum());
                goodsVO.setPurchasePrice(goods.getPurchasePrice());

                images.forEach(image->{
                    if (image.getOrderId().equals(goods.getOrderId().longValue())){
                        goodsVO.setImgUrl(image.getImgUrl());
                    }
                });
                return goodsVO;
            }).collect(Collectors.toList()));

            return indentVO;
        }).collect(Collectors.toList());

        //加入集合
        list.addAll(collect);
    }




    public ApiResult queryPage(Map<String, Object> params) throws ExecutionException, InterruptedException {
        String userId = UserContext.getEndUserId();
        User user = userMapper.selectById(userId);
        String adminId = user.getAdminId();
        String[] adminIds = adminId.split(",");
        List<Admin> admins = adminMapper.selectList(
                new LambdaQueryWrapper<Admin>()
                        .in(Admin::getId, adminIds)
        );
        if (admins == null || admins.isEmpty()) return ApiResult.fail("用户未绑定");

        List<String> collect = admins.stream()
                .map(admin -> String.valueOf(admin.getOrgId()))
                .collect(Collectors.toList());

        params.put("orgIds", collect);  // 注意这里改为orgIds，保持命名一致
        Page<IndentVo> page = new Page<>(Long.parseLong(params.get("page").toString()), Long.parseLong(params.get("pageSize").toString()));
        CompletableFuture<Page<IndentVo>> resPageCompletableFuture = CompletableFuture.supplyAsync(() -> shopIndentMapper.queryPage(page, params), executor);
        Page<IndentVo> resPage = resPageCompletableFuture.get();
        return ApiResult.ok(resPage);
    }

}




